const { Controller } = require('egg');
const fs = require('fs');
const path = require('path');
// const awaitWriteStream = require('await-stream-ready').write;
class PhotoController extends Controller {
    async getPhotoList() {
        const { ctx } = this;
        const imgObjList = this.service.photoService.listAllPhotos();
        ctx.body = {
            data: imgObjList
        }
    }
    async uploadPhoto() {
        const { ctx } = this;
        const {
            path: _path,
            urlSuffix
        } = this.config.photo;
        const file = ctx.request.files[0];
        try {
            fs.copyFileSync(file.filepath, `${_path}/${file.filename}`)
            fs.unlinkSync(file.filepath);
            ctx.body = {
                url: `${urlSuffix}${file.filename}`,
                success: true
            }
        }catch(err){
            ctx.body = {
                success:false,
                errMsg:'上传失败'
            }
        }
        
    }
    async removePhoto() {
        const { filename }
            = this.ctx.request.body;
        const {
            path: _path,
        } = this.config.photo;
        try {
            if (!filename) {
                throw "文件不存在";
            }
            fs.unlinkSync(`${_path}/${filename}`);
            this.ctx.body = {
                success: true
            }
        } catch (err) {
            this.ctx.body = {
                success: false,
                errMsg: typeof (err) == 'string' ? err : '未知错误'
            }
        }
    }
}

module.exports = PhotoController;